package com.cloudbroker.bcs.common.mq.spring.converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.SimpleMessageConverter;

public class DefaultContentTypeSimpleMessageConverter extends SimpleMessageConverter {
    
    private String defaultContentType;
    
    public DefaultContentTypeSimpleMessageConverter() {
        
    }
    
    public DefaultContentTypeSimpleMessageConverter(String defaultContentType) {
        this.defaultContentType = defaultContentType;
    }
    
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        if (StringUtils.isNotBlank(defaultContentType)) {
            MessageProperties messageProperties = message.getMessageProperties();
            if (null == messageProperties) {
                messageProperties = new MessageProperties();
                message = new Message(message.getBody(), messageProperties);
            }
            if (StringUtils.isBlank(messageProperties.getContentType())) {
                messageProperties.setContentType(defaultContentType);
            }
        }
        return super.fromMessage(message);
    }
    
    public String getDefaultContentType() {
        return defaultContentType;
    }
    
    public void setDefaultContentType(String defaultContentType) {
        this.defaultContentType = defaultContentType;
    }
    
}
